// 继电器控制函数
async function controlRelay(relayName, action) {
    try {
        console.log(`控制继电器: ${relayName}, 动作: ${action}`);
        
        const response = await fetch(`/api/relays/${relayName}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ action: action })
        });

        const result = await response.json();
        
        if (result.success) {
            // 更新界面状态
            updateRelayStatus(relayName, result.state);
            showMessage(result.message, 'success');
        } else {
            showMessage('操作失败: ' + result.error, 'error');
        }
    } catch (error) {
        console.error('控制继电器错误:', error);
        showMessage('网络错误: ' + error.message, 'error');
    }
}

// 控制所有继电器
async function controlAll(action) {
    console.log(`控制所有继电器: ${action}`);
    const relays = ['relay_1', 'relay_2', 'relay_3', 'relay_4'];
    
    for (const relayName of relays) {
        await controlRelay(relayName, action);
        // 添加小延迟避免请求过于密集
        await new Promise(resolve => setTimeout(resolve, 100));
    }
}

// 更新继电器状态显示
function updateRelayStatus(relayName, state) {
    const relayCard = document.querySelector(`[data-relay="${relayName}"]`);
    if (relayCard) {
        const statusElement = relayCard.querySelector('.status');
        statusElement.textContent = state ? '开启' : '关闭';
        statusElement.className = `status ${state ? 'on' : 'off'}`;
    }
}

// 显示消息
function showMessage(message, type) {
    // 创建消息元素
    const messageDiv = document.createElement('div');
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 8px;
        color: white;
        font-weight: bold;
        z-index: 1000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        animation: slideIn 0.3s ease;
    `;
    
    if (type === 'success') {
        messageDiv.style.backgroundColor = '#2ecc71';
        messageDiv.innerHTML = `✅ ${message}`;
    } else {
        messageDiv.style.backgroundColor = '#e74c3c';
        messageDiv.innerHTML = `❌ ${message}`;
    }
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动消失
    setTimeout(() => {
        messageDiv.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 300);
    }, 3000);
}

// 添加 CSS 动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(style);

// 页面加载时获取初始状态
document.addEventListener('DOMContentLoaded', async function() {
    console.log('页面加载完成，获取继电器状态...');
    
    try {
        const response = await fetch('/api/relays');
        const result = await response.json();
        
        if (result.success) {
            console.log('继电器状态:', result.data);
            // 更新所有继电器状态
            for (const [relayName, state] of Object.entries(result.data)) {
                updateRelayStatus(relayName, state);
            }
        }
    } catch (error) {
        console.error('获取继电器状态失败:', error);
    }
});

// 继电器控制函数
async function controlRelay(relayName, action) {
    try {
        console.log(`第二步控制继电器: ${relayName}, 动作: ${action}`);
        
        const response = await fetch(`/api/relays/${relayName}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ action: action })
        });

        const result = await response.json();
        
        if (result.success) {
            // 更新界面状态
            updateRelayStatus(relayName, result.state);
            showMessage(result.message, 'success');
            
            // 更新系统信息显示
            updateSystemInfo();
        } else {
            showMessage('操作失败: ' + result.error, 'error');
        }
    } catch (error) {
        console.error('控制继电器错误:', error);
        showMessage('网络错误: ' + error.message, 'error');
    }
}

// 控制所有继电器（只控制启用的）
async function controlAll(action) {
    console.log(`第二步控制所有启用继电器: ${action}`);
    
    try {
        // 先获取系统信息，确定哪些继电器已启用
        const response = await fetch('/api/system/info');
        const systemInfo = await response.json();
        
        if (systemInfo.success) {
            const enabledRelays = systemInfo.data.enabled_relays;
            
            for (const relayName of enabledRelays) {
                await controlRelay(relayName, action);
                // 添加小延迟避免请求过于密集
                await new Promise(resolve => setTimeout(resolve, 200));
            }
        }
    } catch (error) {
        console.error('获取系统信息失败:', error);
    }
}

// 更新系统信息
async function updateSystemInfo() {
    try {
        const response = await fetch('/api/system/info');
        const result = await response.json();
        
        if (result.success) {
            // 可以在这里更新系统状态显示
            console.log('系统信息更新:', result.data);
        }
    } catch (error) {
        console.error('更新系统信息失败:', error);
    }
}

// 页面加载时获取初始状态和系统信息
document.addEventListener('DOMContentLoaded', async function() {
    console.log('第二步页面加载完成，获取继电器状态和系统信息...');
    
    try {
        const [relaysResponse, systemResponse] = await Promise.all([
            fetch('/api/relays'),
            fetch('/api/system/info')
        ]);
        
        const relaysResult = await relaysResponse.json();
        const systemResult = await systemResponse.json();
        
        if (relaysResult.success) {
            console.log('继电器状态:', relaysResult.data);
            // 更新所有继电器状态
            for (const [relayName, state] of Object.entries(relaysResult.data)) {
                updateRelayStatus(relayName, state);
            }
        }
        
        if (systemResult.success) {
            console.log('系统信息:', systemResult.data);
        }
    } catch (error) {
        console.error('初始化数据失败:', error);
    }
});